<?php
/*
 *	Some  database functions
 *	Henrik Volckmer
 */

/* Connects to server properly */
function db_setup()
{
	include('config.php');
	// If using Lighttpd get user/pass from environment variables...
	if ($using_lighttpd)
	{
		$db_username = getenv('MYSQL_USERNAME');
		$db_password = getenv('MYSQL_PASSWORD');
	}
	
	// Try to connect
	$link = mysql_connect($db_server, $db_username, $db_password);
	if (!$link)
	{
		die('Could not connect to database server: '.mysql_error());
	}
	
	// Select the database
	$connect = mysql_select_db($db_database, $link);
	if (!$connect)
	{
		die('Could not select database: '.mysql_error());
	}
	
	return $link;
}

/* Makes sure the connection is closed properly */
function db_close()
{
	$close = mysql_close($link);
	if (!$close)
	{
		die('Could not close connection properly.'.mysql_error());
	}
}

/* Use this instead of mysql_query() so error checking is always performed. */
function db_query($query)
{
	$result = mysql_query($query);
	if (!$result)
	{
		die('Could not perform query: '.mysql_error().'<br/><br/>'.$query);
	}
	return $result;
}

function db_query_as_2d_array($query, $result_type = MYSQL_NUM)
{
	$result = db_query($query);
	
	$arr = array();
	for ($i = 0; $i < mysql_num_rows($result); $i++)
	{
		$arr[$i] = mysql_fetch_array($result, $result_type);	
	}
	return $arr;
}

function db_query_as_array($query, $result_type = MYSQL_NUM)
{
	$result = db_query($query);
	
	$arr = array();
	for ($i = 0; $i < mysql_num_rows($result); $i++)
	{
		$row = mysql_fetch_array($result, $result_type);	
		$arr[$i] = $row[0];
	}
	return $arr;
}

?>